/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.DetermineLogin;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 修改个人信息
 */
@Controller
public class ModifyPersonalInformation {
    private final UserService userService;
    private final CqLogger logger = CqLogger.getInstance();

    public ModifyPersonalInformation(UserService userService) {
        this.userService = userService;
    }

    Map<String, Object> resultMap = new HashMap<>();

    @PostMapping("/api/modifyPersonalInformation")
    public ResponseEntity<Map<String, Object>> modifyPersonalInformation(@RequestBody Map<String, String> requestMap) {

        logger.print(requestMap);

        // 获取用户Id
        Integer userId;

        DetermineLogin determineLogin = DetermineLogin.getInstance(requestMap.get("userAccount"), userService);

        if(determineLogin.startJudge().equals(DetermineLogin.NOT_LOGIN)){
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_NOT_LOGIN);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
            return ResponseEntity.ok(resultMap);
        }else{
            userId = determineLogin.startJudge();
        }

        logger.print(userId);

        try {
            userService.modifyPersonalInformation(userId,
                    requestMap.get("nickName"),
                    requestMap.get("email"),
                    requestMap.get("phone"));
        } catch (Exception e) {
            logger.print("保存用户信息失败：");
            throw new RuntimeException("修改失败", e);
        }
        String avatar = requestMap.get("avatar");

        if (avatar == null || avatar.isEmpty()) {
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_WRONG_USER_ACCOUNT);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_WRONG_USER_ACCOUNT);
            return ResponseEntity.ok(resultMap);
        }

        logger.print(avatar);

        try {
            userService.modifyPersonalAvatar(userId, avatar);
            logger.print("头像保存成功");
        } catch (Exception e) {
            logger.print("头像保存失败：" + e);
            throw new RuntimeException("修改失败", e);
        }

        resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
        resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);

        return ResponseEntity.ok(resultMap);
    }
}
